// namespace
if (window.demo === undefined) {
    var demo = {};
}

demo.mapping = {};

/**
 * get mapped value
 */
demo.mapping.getMappedValue = function(value, mapping, defaultValue) {
    var key = value + "";
    var mappedValue = mapping[key];
    if (mappedValue === undefined) {
        mappedValue = defaultValue || value;
    }

    return mappedValue;
};

// number
demo.mapping.number = {};
demo.mapping.number.decimalPlaces = {
    "integer" : 0,
    "*_low": 1,
    "*_medium": 2,
    "*_high": 5
};

demo.mapping.number.getDecimalPlaces = function(style) {
    var places = 1;
    for (var wildcard in demo.mapping.number.decimalPlaces) {
        var pattern = wildcard.replace("*", "^.*");
        var regExp = new RegExp(pattern);
        if (regExp.test(style) === true) {
            places = demo.mapping.number.decimalPlaces[wildcard];
            break;
        }
    }

    return places;
};

demo.mapping.number.formatToDecimalPlaces = function(value, places) {
    return dojo.number.format(value, {type: "decimal", pattern: "#,##0.###", places: places});
};

/**
 * NumberFormatMapping
 * 
 * var mapping = new NumberFormatMapping(style, nullValue, nanValue).mapping;
 */
demo.mapping.NumberFormatMapping = function(style, nullValue, nanValue) {
    this.style = style || "decimal_low";
    this.nullValue = nullValue;
    this.nanValue = nanValue;
    this._places = demo.mapping.number.getDecimalPlaces(this.style);

    var _self = this;

    this.mapping = function(value) {
        if (value === null) {
            return _self.nullValue || "";
        }

        if (isNaN(value)) {
            return _self.nanValue || "";
        }

        var places = _self._places;
        var mappedValue = demo.mapping.number.formatToDecimalPlaces(value, places);

        if (_self.style.search(/^percentage_/) > -1) {
            mappedValue += "%";
        }

        return mappedValue;
    };
};